package com.library.management.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.library.management.domain.LoginLogs;
import com.library.management.domain.OperationLogs;
import com.library.management.dto.LoginLogQueryDTO;
import com.library.management.dto.OperationLogQueryDTO;
import com.library.management.dto.OperationLogDetailDTO;
import com.library.management.service.LoginLogsService;
import com.library.management.service.OperationLogsService;
import com.library.management.util.Result;
import cn.dev33.satoken.annotation.SaCheckRole;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 系统日志控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/logs")
@Api(tags = "系统日志接口", description = "提供登录日志和操作日志查询功能")
public class LogsController {

    @Autowired
    private LoginLogsService loginLogsService;
    
    @Autowired
    private OperationLogsService operationLogsService;

    /**
     * 查询登录日志列表
     * @param queryDTO 查询参数
     * @return 登录日志列表
     */
    @ApiOperation("查询登录日志列表")
    @SaCheckRole("admin")
    @GetMapping("/login")
    public Result<Page<LoginLogs>> getLoginLogs(LoginLogQueryDTO queryDTO) {
        log.info("查询登录日志列表: pageNum={}, pageSize={}, userId={}, startTime={}, endTime={}", 
                queryDTO.getPageNum(), queryDTO.getPageSize(), queryDTO.getUserId(), 
                queryDTO.getStartTime(), queryDTO.getEndTime());
        
        Page<LoginLogs> page = loginLogsService.getLoginLogPage(queryDTO);
        return Result.success(page);
    }

    /**
     * 查询操作日志列表
     * @param queryDTO 查询参数
     * @return 操作日志列表（包含详细信息）
     */
    @ApiOperation("查询操作日志列表")
    @SaCheckRole("admin")
    @GetMapping("/operation")
    public Result<Page<OperationLogDetailDTO>> getOperationLogs(OperationLogQueryDTO queryDTO) {
        log.info("查询操作日志列表: pageNum={}, pageSize={}, actionType={}, operatorId={}", 
                queryDTO.getPageNum(), queryDTO.getPageSize(), 
                queryDTO.getActionType(), queryDTO.getOperatorId());
        
        Page<OperationLogDetailDTO> page = operationLogsService.getOperationLogDetailPage(queryDTO);
        
        // 检查结果中是否有操作者用户名
        if (page != null && page.getRecords() != null && !page.getRecords().isEmpty()) {
            boolean hasOperatorName = page.getRecords().stream()
                    .anyMatch(dto -> dto.getOperatorName() != null && !dto.getOperatorName().startsWith("未知用户"));
            log.info("操作日志查询结果: 记录数={}, 是否包含用户名={}", 
                    page.getRecords().size(), hasOperatorName);
        }
        
        return Result.success(page);
    }
} 